#!/usr/bin/python

import os
import sys

def ShowError(msg):
	print msg
	exit(1)

if len(sys.argv) < 4:
	ShowError('usage: combinearff srcarff1 srcarff2 outputarff\nnote: The src should have same attributes!')

infile1 = open(sys.argv[1], 'r')
infile2 = open(sys.argv[2], 'r')
ofile = open(sys.argv[3], 'w')

inline1 = infile1.readlines()
inline2 = infile2.readlines()

index = 0
startdata = 0
while True:
	if index == 0:
		assert(inline1[index] == inline2[index])
		ofile.write(inline1[index])
	elif startdata == 0 and inline1[index].startswith('@'):
		assert(inline2[index].startswith('@'))
		if inline1[index].strip() == '@data' and inline2[index].strip() == '@data':
			ofile.write(inline1[index])
			startdata = 1
		else:
			attr1 = inline1[index].strip().split(' ')
			attr2 = inline2[index].strip().split(' ')
			assert(attr1[0] == '@attribute')
			assert(attr2[0] == '@attribute')
			assert(attr1[1] == attr2[1])
			if attr1[2].startswith('{'):
				assert(attr2[2].startswith('{'))
				symble1 = attr1[2][1:-1].split(',')
				symble2 = attr2[2][1:-1].split(',')
				symset = set([])
				for sym in symble1:
					symset.add(sym)
				for sym in symble2:
					symset.add(sym)
				outputline = ''
				for sym in symset:
					outputline += sym + ','
				ofile.write('@attribute ' + attr1[1] + ' {' + outputline[0:-1] + '}\n')
			else:
				assert(attr1[2] == attr1[2])
				ofile.write(inline1[index])
	elif startdata == 1:
		if index < len(inline1):
			ofile.write(inline1[index])
		if index < len(inline2):
			ofile.write(inline2[index])
	else:
		ShowError('Wrong format on line: ' + str(index))
	index += 1

	if (index >= len(inline1) and index >= len(inline2)):
		break

ofile.close()
infile2.close()
infile1.close()
